# -*- coding: utf-8 -*-
# 以上可以转代码上的中文为正常码
import os
import threading
from concurrent.futures import ThreadPoolExecutor, Future
import itertools
import string

from tqdm import tqdm

import time

exit_event = threading.Event()

def process_item(item):
    # 这里可以是你需要对每个元素进行的处理
    pwd = "".join(item)
    #print(f"尝试：{pwd}")
    # time.sleep(2)
    #if pwd == ' ':
    if pwd == '12Ab':
        exit_event.set()
        print(f"\r密码是：{pwd}")
    # print(f"结束：{pwd}")


def run(iterator):
    with ThreadPoolExecutor(threads) as executor:
        executor.map(process_item, iterator)
    while True:
        # 检查是否需要退出
        if exit_event.is_set():
            print("主进程收到终止信号，正在退出...")
            break
        print("主进程正在运行...")


if __name__ == "__main__":
    try:
        # 假设你有一个迭代器 iterator
        threads = 12
        default_threads = min(32, (os.cpu_count() or 1) + 4)
        print(default_threads)
        password_length = 4
        #password_types = ['ascii_letters', 'digits', 'punctuation']
        password_types = ['ascii_letters', 'digits']
        characters = "".join([getattr(string, k) for k in password_types])
        # string.ascii_letters + string.digits + string.punctuation
        print(characters)
        password_combinations = itertools.product(characters, repeat=password_length)
        run(tqdm(password_combinations, total=len(characters)**password_length, desc="Processing", ncols=100, ascii=True))
    except KeyboardInterrupt:
        print("强制中止...")
    finally:
        print("退出主进程。")